<template>
  <div>
    <el-card class="box-card">
      <el-button size="mini" style="float:right;" @click="actionRefresh">刷新</el-button>
      <el-input placeholder="过滤端口或进程" size="mini" style="width:300px;" v-model="filterText"></el-input>
    </el-card>

    <el-table :data="filtedPorts">
      <el-table-column prop="port" label="端口"></el-table-column>
      <el-table-column prop="proto" label="协议"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column prop="pid" label="PID"></el-table-column>
      <el-table-column prop="program" label="进程"></el-table-column>
    </el-table>
  </div>
</template>
<script>
import RegexMatch from '../../utils/RegexMatch.js'
export default {
    data() { 
        return {
            filterText : null,
            ports : [],
        };
    },
    computed : {
        filtedPorts () {
            if ( null == this.filterText || '' == this.filterText.trim() ) {
                return this.ports;
            }

            let ports = [];
            for ( let i=0; i<this.ports.length; i++ ) {
                if ( this.ports[i].port == this.filterText ||  -1 != this.ports[i].program.indexOf(this.filterText) ) {
                    ports.push(this.ports[i]);
                }
            }
            return ports;
        },
    },
    async mounted() {
        await this.refresh();
    },
    methods : {
        /** */
        async actionRefresh() {
            await this.refresh();
        },

        /** 刷新列表 */
        async refresh () {
            let server = this.$store.getters.serverCurrent;
            let client = await server.getSshClient();
            let netstat = await client.exec('sudo netstat -nltup');
            netstat = netstat.trim().split('\r\n');
            netstat.shift(); netstat.shift();

            this.ports = [];
            for ( let i=0; i<netstat.length; i++ ) {
                let line = netstat[i].trim();
                let port = RegexMatch.match('netstat-nltup', line);
                if ( null != port ) {
                    this.ports.push(port);
                }
            }
        },
    },
}
</script>